#!/bin/bash
#install-ansible  2022-04-19

DIR=$(pwd)

Tips_title()
{
        printf '\033[1;32m%s\033[0m\n' "$1"
}

Tips_body()
{
        printf '\033[36m%s\033[0m\n' "$1"
}

Install_Check()
{	
	#检查是否为root
	who=`whoami`
	group=`groups $who`
	if [[ $who =~ "root" ]];then
        echo ""
	else
        echo -e "\n\033[33m 当前用户$who没有root权限,请使用root用户登录安装 \033[0m"
		End_Install
	fi

	#检查是否已经安装ansible
	if rpm -q ansible &> /dev/null || [[ -d "/etc/ansible/" ]];then
		echo -n -e "\n\033[31m 已经安装ansible,继续安装请按Y/y,退出安装请按其他任意键:\033[0m"
		read CH
				
		if [[ "$CH" != "Y" ]] && [[ "$CH" != "y" ]];then
			echo -e "\n\033[33m 退出安装 \033[0m"
			End_Install
		else
			mv /etc/ansible{,.bak}
			rpm -e ansible
		fi
	fi	
}

Configure_EPEL()
{
    #配置阿里云EPEL源
    wget -O /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo
    
    #清空和更新本地yum缓存
    yum clean all && yum makecache
}

Install_Ansible()
{
	#安装ansible
	yum install -y ansible

    #检查是否安装成功
	rpm -q ansible &>/dev/null
	if [ $? != 0 ]; then
		echo -e "\n\033[41;30m 安装失败 \033[0m"
		End_Install
	fi

	#配置ansible
	sed -i 's/#host_key_checking = False/host_key_checking = False/g' /etc/ansible/ansible.cfg
}

Show_Tips()
{
Tips_body  ""
Tips_body  "================================================================"
Tips_body  ""
Tips_title "                     ***Ansible Tips***                      "
Tips_body  ""
Tips_body  "##添加host"
Tips_body  "vim /etc/ansible/hosts添加host，参考:"
Tips_body  "[server]"
Tips_body  "192.168.1.100 ansible_ssh_user=root ansible_ssh_pass=password"
Tips_body  ""
Tips_body  "##测试ping"
Tips_body  "ansible server -m ping"
Tips_body  ""
Tips_body  "##执行命令"
Tips_body  'ansible server -m command -a "ifconfig"'
Tips_body  ""
Tips_body  "##将主控的/root/rpm目录推送到指定节点的/tmp目录下"
Tips_body  "ansible server -m synchronize -a 'src=/root/rpm dest=/tmp compress=yes'"
Tips_body  ""
Tips_body  "##将192.168.1.100节点的/tmp/a目录拉取到主控节点的/root目录下"
Tips_body  "ansible 192.168.1.100 -m synchronize -a 'mode=pull src=/tmp/a dest=/root/'"
Tips_body  "参数说明:"
Tips_body  "delete=yes      使两边的内容一样（即以推送方为主）"
Tips_body  "compress=yes    开启压缩，默认为开启"
Tips_body  "--exclude=.git  忽略同步.git结尾的文件"
Tips_body  ""
Tips_body  "================================================================"
}

End_Install()
{
	#删除文件
	rm -rf $DIR/install-ansible-el7.sh
	exit
}

Install_Check
Configure_EPEL
Install_Ansible
Show_Tips
End_Install